package com.java.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamTest02 {
    public static void doFind(List<Integer> list){
        //Optional<Integer> first = list.stream().sorted().findFirst();
        Optional<Integer> first = list.stream().filter(i->i%2!=0).findAny();
        System.out.println(first.get());
    }
    /**match操作*/
    public static void doMatch(List<Integer> list){
        boolean b = list.stream()
                //.allMatch(i -> i % 2 == 0); //是否匹配所有
                // .anyMatch(i->i%2==0);//是否有匹配的
                    .noneMatch(i->i%2==0);//是否没有匹配项
        System.out.println(b);
    }
    /**Reduce操作(规约操作)*/
    public static void doReduce(List<Integer> list){
        Integer sum=list.stream().reduce(0,(x,y)->{return x+y;});
        System.out.println(sum);
    }
    //去除list集合中的空格
    public static void doCollect(){
        List<String> list=Arrays.asList("A","AB"," ","ABC");
        List<String> collect =
                list.stream()
                        .filter((item) -> item.trim().length() != 0)
                        .collect(Collectors.toList());
        System.out.println(collect);
    }
    //Stream中的forEach操作是顺序消费吗？
    //foreach操作会快速失败吗
    public static void doForEach(){
        List<Integer> list= new ArrayList<>();
        list.add(1); list.add(2); list.add(3); list.add(4);
        //list.stream().forEach(System.out::println);//非并行流是顺序消费
        //list.parallelStream().forEach(System.out::println);并行流不是顺序消费
        //并行流希望顺序消费可以执行forEachOrdered
        //list.parallelStream().forEachOrdered(System.out::println);
        //foreach操作会快速失败吗?
//        list.stream().forEach(item->{
//            list.add(13);
//            System.out.println(item);
//        });
        Stream<Integer> stream = list.stream();
        list.add(13);
        stream.forEach(System.out::println);
    }


    public static void main(String[] args) {
        List<Integer> list= Arrays.asList(15,11,12,13,14,10);
        //doMatch(list);
        //doFind(list);
        //doReduce(list);
        //doCollect();
        doForEach();
    }
}
